import React, { useState } from 'react';
import { Form, Button, Card, Alert } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import AuthService from '../services/AuthService';

const Register = () => {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [fullName, setFullName] = useState('');
  const [role, setRole] = useState('ROLE_USER'); // 默认为普通用户
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [successful, setSuccessful] = useState(false);
  const navigate = useNavigate();

  const validateForm = () => {
    if (!username || !password || !confirmPassword || !fullName) {
      setMessage('请填写所有必填字段');
      return false;
    }

    if (password !== confirmPassword) {
      setMessage('两次输入的密码不一致');
      return false;
    }

    if (password.length < 6) {
      setMessage('密码长度至少为6个字符');
      return false;
    }

    return true;
  };

  const handleRegister = (e) => {
    e.preventDefault();
    setMessage('');
    setSuccessful(false);
    setLoading(true);

    if (!validateForm()) {
      setLoading(false);
      return;
    }

    // 根据选择的角色调用不同的注册方法
    const registerMethod = role === 'ROLE_ADMIN' 
      ? AuthService.registerAdmin 
      : AuthService.register;

    registerMethod(username, email, password, fullName)
      .then(response => {
        if (response.data.code === 200) {
          setMessage(role === 'ROLE_ADMIN' ? '管理员注册成功！' : '用户注册成功！您现在可以登录了');
          setSuccessful(true);
          setTimeout(() => {
            navigate('/login');
          }, 2000);
        } else {
          setMessage(response.data.message || '注册失败，请稍后再试');
          setSuccessful(false);
          setLoading(false);
        }
      })
      .catch(error => {
        const resMessage = (error.response && 
                           error.response.data && 
                           error.response.data.message) || 
                           error.message || 
                           error.toString();
        setMessage(resMessage);
        setSuccessful(false);
        setLoading(false);
      });
  };

  return (
    <Card className="p-4 mx-auto mt-5" style={{ maxWidth: '500px', border: 'none', boxShadow: '0 0 20px rgba(0,0,0,0.1)' }}>
      <Card.Body className="p-4">
        <h2 className="text-center mb-4" style={{ color: '#2e7d32', fontWeight: '600' }}>账号注册</h2>
        
        {message && (
          <Alert variant={successful ? "success" : "danger"} className="mb-4" style={{ borderRadius: '8px' }}>
            {message}
          </Alert>
        )}

        <Form onSubmit={handleRegister} className="px-2">
          <Form.Group className="mb-4" controlId="formRole">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>账号类型 <span style={{ color: '#dc3545' }}>*</span></Form.Label>
            <Form.Select
              value={role}
              onChange={(e) => setRole(e.target.value)}
              disabled={loading}
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            >
              <option value="ROLE_USER">普通用户</option>
              <option value="ROLE_ADMIN">管理员</option>
            </Form.Select>
          </Form.Group>

          <Form.Group className="mb-4" controlId="formUsername">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>用户名 <span style={{ color: '#dc3545' }}>*</span></Form.Label>
            <Form.Control
              type="text"
              placeholder="请输入用户名"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              disabled={loading}
              required
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            />
          </Form.Group>

          <Form.Group className="mb-4" controlId="formEmail">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>电子邮箱</Form.Label>
            <Form.Control
              type="email"
              placeholder="请输入电子邮箱"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={loading}
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            />
          </Form.Group>

          <Form.Group className="mb-4" controlId="formFullName">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>全名 <span style={{ color: '#dc3545' }}>*</span></Form.Label>
            <Form.Control
              type="text"
              placeholder="请输入您的全名"
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              disabled={loading}
              required
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            />
          </Form.Group>

          <Form.Group className="mb-4" controlId="formPassword">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>密码 <span style={{ color: '#dc3545' }}>*</span></Form.Label>
            <Form.Control
              type="password"
              placeholder="请输入密码（至少6个字符）"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={loading}
              required
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            />
          </Form.Group>

          <Form.Group className="mb-4" controlId="formConfirmPassword">
            <Form.Label style={{ fontWeight: '500', color: '#333' }}>确认密码 <span style={{ color: '#dc3545' }}>*</span></Form.Label>
            <Form.Control
              type="password"
              placeholder="请再次输入密码"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              disabled={loading}
              required
              style={{ 
                padding: '0.75rem',
                borderRadius: '8px',
                border: '1px solid #ced4da',
                fontSize: '1rem'
              }}
            />
          </Form.Group>

          <Button 
            variant="success" 
            type="submit" 
            className="w-100 py-3 mt-3" 
            disabled={loading}
            style={{
              backgroundColor: '#2e7d32',
              borderColor: '#2e7d32',
              borderRadius: '8px',
              fontSize: '1.1rem',
              fontWeight: '500',
              boxShadow: '0 2px 4px rgba(46,125,50,0.2)',
              transition: 'all 0.2s ease'
            }}
            onMouseOver={(e) => e.target.style.backgroundColor = '#1b5e20'}
            onMouseOut={(e) => e.target.style.backgroundColor = '#2e7d32'}
          >
            {loading ? '注册中...' : role === 'ROLE_ADMIN' ? '注册管理员' : '注册用户'}
          </Button>
        </Form>
        
        <div className="mt-4 text-center" style={{ color: '#666' }}>
          <span>已有账号？</span>{' '}
          <Button 
            variant="link" 
            className="p-0" 
            onClick={() => navigate('/login')}
            disabled={loading}
            style={{
              color: '#2e7d32',
              textDecoration: 'none',
              fontWeight: '500',
              fontSize: '1rem'
            }}
            onMouseOver={(e) => e.target.style.color = '#1b5e20'}
            onMouseOut={(e) => e.target.style.color = '#2e7d32'}
          >
            立即登录
          </Button>
        </div>
      </Card.Body>
    </Card>
  );
};

export default Register; 